package VMM;
import java.util.HashMap;
import java.util.Set;

/**
 * A class to model a TLB which makes use of lru replacement policy
 * 
 * @author allanwatson
 * 
 * @changelog 15/2/12 extra remove statement to maintain set as well as hashmap
 *            16/2/12 added check and print statement for over capacity 17/2/12
 *            added check for invalid number. check for if it contains the
 *            pageno already, then update. 18/2/12 removed unecessary check for
 *            frame number. Code cleanup and comment
 */
public class TLBlru implements ITLB {

	private int capacity;
	private HashMap<Integer, Integer> map;
	private Set<Integer> keySet;

	public TLBlru(int cap) {
		capacity = cap;
		map = new HashMap<Integer, Integer>(cap);
		keySet = map.keySet();
	}

	/**
	 * Use a queue to keep the order
	 */
	public void put(int pageNo, int frameNo) {

		if (map.size() == capacity)
			replace();// replace an entry when you reach full capacity

		else if (containsPage(pageNo))
			map.remove(pageNo);// if page already exists remove

		map.put(pageNo, frameNo);

	}

	/**
	 * Remove item that has been least recently used, should be at top of map
	 */
	private void replace() {
		Object[] arr = keySet.toArray();
		keySet.remove(arr[0]);
		map.remove(arr[0]);
	}

	/**
	 * Determines whether a page is in the TLB
	 */
	public boolean containsPage(int pageNo) {
		return map.containsKey(pageNo);
	}

	/**
	 * Returns the associated page of frame, moving to top of map
	 */
	public int getFrameNo(int pageNo) {
		int fN = (Integer) map.remove(pageNo);// remove from map
		map.put(pageNo, fN);// add to end of map

		return (Integer) map.get(pageNo);
	}
}
